﻿Imports System.ComponentModel
Imports System.Net.NetworkInformation
Imports HslCommunication.LogNet
Imports HslCommunication.Profinet.Siemens
Public Class frm_HB_LHJ
    Private g_szInitFileName As String
    Private logfile As ILogNet
    Private plc As SiemensS7Net
    Private objDB As New clsEquit_HB_LHJ
    Private Power_Inserted As Boolean

    Public Sub New()
        AddHandler AppDomain.CurrentDomain.AssemblyResolve, New ResolveEventHandler(AddressOf CurrentDomain_AssemblyResolve)
        ' 此调用是设计器所必需的。
        InitializeComponent()

        ' 在 InitializeComponent() 调用之后添加任何初始化。

    End Sub

    Private Function CurrentDomain_AssemblyResolve(sender As Object, args As ResolveEventArgs) As System.Reflection.Assembly
        Dim dllName As String = If(args.Name.Contains(","), args.Name.Substring(0, args.Name.IndexOf(","c)), args.Name.Replace(".dll", ""))
        dllName = dllName.Replace(".", "_")
        If dllName.EndsWith("_resources") Then
            Return Nothing
        End If
        Dim rm As New System.Resources.ResourceManager([GetType].Namespace & ".Resources", System.Reflection.Assembly.GetExecutingAssembly())
        Dim bytes As Byte() = DirectCast(rm.GetObject(dllName), Byte())
        Return System.Reflection.Assembly.Load(bytes)
    End Function
    Private Sub frmHB_LHJ_Load(sender As Object, e As EventArgs) Handles Me.Load
        If Not HslCommunication.Authorization.SetAuthorizationCode("e3e27344-1a9f-4d8b-b4fc-da5cae4b99bf") Then

        End If

        Me.g_szInitFileName = My.Application.Info.DirectoryPath & "\LHJ.ini"
        logfile = New LogNetDateTime(Application.StartupPath & "\\Logs", GenerateMode.ByEveryDay)
        connectDB()

        '读PLC
        Dim plcIP As String = GetIniFile("IP", "PLC", "", Me.g_szInitFileName)
        plc = New SiemensS7Net(SiemensPLCS.S200Smart)
        With plc
            .IpAddress = plcIP
            .Port = 102
            .SetPersistentConnection()
        End With

        readPLC()
        Timer1.Interval = 3 * 60 * 1000
        Timer1.Start()
    End Sub

    Private Sub readPLC()

        Dim _en As New en_equit_hb_LHJ_item
        dgvErr.DataSource = Nothing
        dgvErr.Refresh()

        'Dim dt As DataTable = objDB.selectErrorAll()
        'If dt.Rows.Count = 0 Then
        '    Exit Sub
        'Else
        '    dgv.DataSource = dt
        'End If

        'Dim plcIP As String = GetIniFile("IP", "PLC", "", Me.g_szInitFileName)
        'Dim ping = New Net.NetworkInformation.Ping()
        'Dim pingResult1F As Net.NetworkInformation.PingReply = ping.Send(plcIP)
        'Try
        '    If pingResult1F.Status <> Net.NetworkInformation.IPStatus.Success Then
        '        With _en
        '            .save_time = Now                                   ' 保存时间
        '            .power_on = False           ' 开关机状态
        '            If .power_on = False And Power_Inserted = True Then
        '                Dim dt As DataTable = objDB.selectErrorAll()
        '                If dt.Rows.Count = 0 Then
        '                    Exit Sub
        '                Else
        '                    dgv.DataSource = dt
        '                End If

        '                Exit Sub
        '            ElseIf .power_on = False And Power_Inserted = False Then
        '                Power_Inserted = True
        '            End If

        '            If .power_on = False Then
        '                objDB.insert(_en)
        '                Dim dt As DataTable = objDB.selectErrorAll()
        '                If dt.Rows.Count = 0 Then
        '                    Exit Sub
        '                Else
        '                    dgv.DataSource = dt
        '                End If
        '                Exit Sub
        '            End If
        '        End With
        '    End If
        'Catch ex As Exception

        'End Try

        Dim dtData As DataTable = objDB.selectData()
        dgvData.DataSource = dtData

        Dim dtAddress As DataTable = objDB.selectErrorAddressAll()
        If dtAddress.Rows.Count > 0 Then
            dtAddress.Columns.Add("value")
        End If

        Try
            With _en
                'Q0.7	BOOL	主排风机 运行中继
                'Q1.1	BOOL	脱附风机 运行中继
                If plc.ReadBool("Q0.7").IsSuccess Or plc.ReadBool("Q1.1").IsSuccess Then
                    .power_on = plc.ReadBool("Q0.7").Content Or plc.ReadBool("Q1.1").Content ' 开关机状态
                Else
                    .power_on = False
                End If
                If .power_on = True Then ' 开关机状态
                    For Each _drAddress As DataRow In dtAddress.Rows

                        Dim err As Boolean = plc.ReadBool(_drAddress("plc_address")).Content
                        _drAddress("value") = err
                        If err Then
                            objDB.insertError(_drAddress("plc_address"), _drAddress("note"))
                        End If
                    Next
                End If
                '检查未处理完的故障是否已OK
                Dim dtErrUnfinished As DataTable = objDB.selectErrorForUnfinished
                For Each drErrUnfinished As DataRow In dtErrUnfinished.Rows
                    Dim _status As Boolean = plc.ReadBool(drErrUnfinished("plc_add")).Content
                    If _status = False Then
                        objDB.setErrorFinished(drErrUnfinished("sys_id"))
                    End If
                Next
                dgvErr.DataSource = dtAddress
                '保存数据库

                .save_time = Now   ' 保存时间

                If .power_on = False And Power_Inserted = True Then
                    Exit Sub
                ElseIf .power_on = False And Power_Inserted = False Then
                    Power_Inserted = True
                End If
                If .power_on = False Then
                    objDB.insert(_en)
                    Exit Sub
                End If
                If plc.ReadBool("V7000.3").Content Then
                    .run_modle = 0                             ' V7000.3	自动模式
                ElseIf plc.ReadBool("V7000.2").Content Then
                    .run_modle = 1                             ' V7000.2	手动模式
                End If
                IIf(plc.ReadBool(" V7007.0 ").Content, .FZXT01 = 1, .FZXT01 = 0)
                IIf(plc.ReadBool(" V7007.2 ").Content, .FZXT02 = 1, .FZXT02 = 0)
                IIf(plc.ReadBool(" V7007.4 ").Content, .FZXT03 = 1, .FZXT03 = 0)
                IIf(plc.ReadBool(" V7007.6 ").Content, .FZXT04 = 1, .FZXT04 = 0)
                IIf(plc.ReadBool(" V7008.0 ").Content, .FZXT05 = 1, .FZXT05 = 0)
                IIf(plc.ReadBool(" V7008.2 ").Content, .FZXT06 = 1, .FZXT06 = 0)
                IIf(plc.ReadBool(" V7008.4 ").Content, .FZXT07 = 1, .FZXT07 = 0)
                IIf(plc.ReadBool(" V7008.6 ").Content, .FZXT08 = 1, .FZXT08 = 0)
                IIf(plc.ReadBool(" V7009.0 ").Content, .FZXT09 = 1, .FZXT09 = 0)
                IIf(plc.ReadBool(" V7009.2 ").Content, .FZXT10 = 1, .FZXT10 = 0)
                IIf(plc.ReadBool(" V7009.4 ").Content, .FZXT11 = 1, .FZXT11 = 0)
                IIf(plc.ReadBool(" V7009.6 ").Content, .FZXT12 = 1, .FZXT12 = 0)
                IIf(plc.ReadBool(" V7010.0 ").Content, .FZXT13 = 1, .FZXT13 = 0)
                IIf(plc.ReadBool(" V7010.2 ").Content, .FZXT14 = 1, .FZXT14 = 0)
                IIf(plc.ReadBool(" V7010.4 ").Content, .FZXT15 = 1, .FZXT15 = 0)
                IIf(plc.ReadBool(" V7010.6 ").Content, .FZXT16 = 1, .FZXT16 = 0)
                IIf(plc.ReadBool(" V7011.0 ").Content, .FZXT17 = 1, .FZXT17 = 0)
                IIf(plc.ReadBool(" V7011.2 ").Content, .FZXT18 = 1, .FZXT18 = 0)
                IIf(plc.ReadBool(" V7011.4 ").Content, .FZXT19 = 1, .FZXT19 = 0)
                IIf(plc.ReadBool(" V7011.6 ").Content, .FZXT20 = 1, .FZXT20 = 0)
                IIf(plc.ReadBool(" V7012.0 ").Content, .FZXT21 = 1, .FZXT21 = 0)
                IIf(plc.ReadBool(" V7012.2 ").Content, .FZXT22 = 1, .FZXT22 = 0)
                IIf(plc.ReadBool(" V7012.4 ").Content, .FZXT23 = 1, .FZXT23 = 0)
                IIf(plc.ReadBool(" V7012.6 ").Content, .FZXT24 = 1, .FZXT24 = 0)


                '    .temp_tf = plc.ReadFloat("VD3020").Content ' 脱附温度
                '    ' 箱体温度T7-T12
                '    .temp_box_t7 = plc.ReadFloat("VD3024").Content
                '    .temp_box_t8 = plc.ReadFloat("VD3028").Content
                '    .temp_box_t9 = plc.ReadFloat("VD3032").Content
                '    .temp_box_t10 = plc.ReadFloat("VD3036").Content
                '    .temp_box_t11 = plc.ReadFloat("VD3040").Content
                '    .temp_box_t12 = plc.ReadFloat("VD3044").Content

                '    .temp_jr = plc.ReadFloat("VD3004").Content ' 加热温度
                '    .temp_rs = plc.ReadFloat("VD3008").Content  ' 燃烧温度

                '    .po3_pa = plc.ReadFloat("VD3060").Content
                '    .po4_pa = plc.ReadFloat("VD3064").Content
                '    .po5_pa = plc.ReadFloat("VD3068").Content

                '    'V120.0 BOOL 故障指示触发 P03 过滤箱1#过滤压差 预警
                '    'V120.1 BOOL 故障指示触发 P04 过滤箱2#过滤压差 预警
                '    'V120.2 BOOL 故障指示触发 P05 过滤箱3#过滤压差 预警
                '    'V121.0 BOOL 故障指示触发 P03 过滤箱1#过滤压差 停机
                '    'V121.1 BOOL 故障指示触发 P04 过滤箱2#过滤压差 停机
                '    'V121.2 BOOL 故障指示触发 P05 过滤箱3#过滤压差 停机
                '    '以上任何一个为true就为故障 过滤器状态:0为正常，1为故障
                '    If plc.ReadBool("V120.0").Content = False And
                '      plc.ReadBool("V120.1").Content = False And
                '      plc.ReadBool("V120.2").Content = False And
                '      plc.ReadBool("V121.0").Content = False And
                '      plc.ReadBool("V121.1").Content = False And
                '      plc.ReadBool("V121.2").Content = False Then
                '        .filter_status = 0
                '    Else
                '        .filter_status = 1
                '    End If

            End With
            Power_Inserted = False
            objDB.insert(_en)

        Catch ex As Exception

            logfile.WriteError("Connect Failed:" & ex.Message)
        End Try

    End Sub

    Public Sub connectDB()
        'イニシャルファイル情報取得

        g_Server.szDrive = GetIniFile("SERVER", "DRIVE", "PostgreSQL ANSI", g_szInitFileName)
        g_Server.szIPadr = GetIniFile("SERVER", "IP", "", g_szInitFileName)
        g_Server.szDbn = GetIniFile("SERVER", "DBN", "ZHENANSF", g_szInitFileName)
        g_Server.szUid = GetIniFile("SERVER", "UID", "sa", g_szInitFileName)
        g_Server.szPas = GetIniFile("SERVER", "PAS", "sa", g_szInitFileName)
        g_Server.iOver = CInt(GetIniFile("SERVER", "OVER", "-1", g_szInitFileName))

        '得到当前用户名
        g_LoginUser = GetIniFile("LOGIN", "user", "admin", g_szInitFileName)

        If False = g_fDBconnect And 0 = g_iDBconnResult Then
            If "" = g_Server.szIPadr Or "0.0.0.0" = g_Server.szIPadr Then
            Else
                g_fDBconnect = True

                'データベース接続
                With g_Server
                    g_iDBconnResult = DBacs.Connect(.szDrive, .szIPadr, .szDbn, .szUid, .szPas, .iOver)
                    If 1 <> g_iDBconnResult Then
                        .szDrive = CStr(IIf("PostgreSQL" = .szDrive, "PostgreSQL ANSI", "PostgreSQL"))
                        g_iDBconnResult = DBacs.Connect(.szDrive, .szIPadr, .szDbn, .szUid, .szPas, .iOver)
                    End If
                End With
            End If
        End If

        setAllErrMsg()
    End Sub

    Private Sub 提取ToolStripMenuItem_Click(sender As Object, e As EventArgs)
        readPLC()
    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        readPLC()
    End Sub

    Private Sub 关闭ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 关闭ToolStripMenuItem.Click
        If MsgBox("如关闭系统，则停止硫化机设备监控！" & vbCrLf & "确定要关闭吗？", 4, Me.Text) = MsgBoxResult.Yes Then
            RemoveHandler Me.Closing, AddressOf frmHB_LHJ_Closing
            Timer1.Stop()
            Close()
        End If
    End Sub

    Private Sub frmHB_LHJ_Closing(sender As Object, e As CancelEventArgs) Handles Me.Closing
        e.Cancel = True
    End Sub
End Class
Public Class clsEquit_HB_LHJ
    Public Function selectErrorAddressAll() As DataTable
        Dim szSql As String = ""
        Dim rtn As DataTable

        szSql &= "SELECT * FROM sf.b_equip_info_hb_LHJ_error_address "
        rtn = DBacs.ExecuteSql(szSql, -1)
        If IsNothing(rtn) Then
            selectErrorAddressAll = New DataTable
        Else
            selectErrorAddressAll = rtn
        End If
        Return rtn
    End Function
    Public Function selectErrorForUnfinished() As DataTable
        Dim szSql As String = ""
        Dim rtn As DataTable

        szSql &= "SELECT * FROM sf.b_equip_info_hb_LHJ_error where  status =1  "
        rtn = DBacs.ExecuteSql(szSql, -1)
        If IsNothing(rtn) Then
            selectErrorForUnfinished = New DataTable
        Else
            selectErrorForUnfinished = rtn
        End If
        Return rtn
    End Function
    Public Sub setErrorFinished(sys_id As Integer)
        Dim szSql As String = String.Empty
        szSql = "update sf.b_equip_info_hb_lhj_error set end_time=? ,status=2 where sys_id=?"
        DBacs.ExecuteUpdateSql(szSql, -1, Now, sys_id)
    End Sub
    Public Function insertError(plc_add As String, errorInfo As String) As Integer
        Dim szSql As String = String.Empty
        Dim rtn As Integer
        Dim dtErr As DataTable
        Try

            szSql = "select * from sf.b_equip_info_hb_LHJ_error where status =1 and plc_add=?"
            dtErr = DBacs.ExecuteSql(szSql, -1, plc_add)
            If dtErr.Rows.Count > 0 Then
            Else
                szSql = "INSERT INTO sf.b_equip_info_hb_lhj_error(begin_time,  plc_add, error, status) VALUES (?,?,?,1)"
                rtn = DBacs.ExecuteUpdateSql(szSql, -1, Now, plc_add, errorInfo)
            End If

        Catch ex As Exception
            rtn = -2
        End Try
        Return rtn
    End Function

    Public Function selectData() As DataTable
        Dim szSql As String = ""
        Dim rtn As DataTable

        szSql &= "SELECT * FROM sf.b_equip_info_hb_lhj order by save_time DESC "
        rtn = DBacs.ExecuteSql(szSql, -1)
        If IsNothing(rtn) Then
            selectData = New DataTable
        Else
            selectData = rtn
        End If
        Return rtn
    End Function
    Public Function insert(_en As en_equit_hb_LHJ_item) As Integer
        Dim szSql As String = String.Empty
        Dim rtn As Integer

        Try
            szSql &= "INSERT INTO sf.b_equip_info_hb_lhj(save_time,power_on,run_modle,"
            szSql &= "FZXT01,FZXT02,FZXT03,FZXT04,FZXT05,FZXT06,FZXT07,FZXT08,FZXT09,FZXT10,FZXT11,FZXT12,FZXT13,FZXT14,FZXT15,FZXT16,FZXT17,FZXT18,FZXT19,FZXT20,FZXT21,FZXT22,FZXT23,FZXT24) "
            szSql &= "VALUES ( ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? ,? ,? , ?, ?, ?, ?, ?, ?, ?)"

            With _en
                rtn = DBacs.ExecuteUpdateSql(szSql, -1, .save_time, .power_on, .run_modle,
                .FZXT01, .FZXT02, .FZXT03, .FZXT04, .FZXT05, .FZXT06, .FZXT07, .FZXT08, .FZXT09, .FZXT10, .FZXT11, .FZXT12, .FZXT13, .FZXT14, .FZXT15, .FZXT16, .FZXT17, .FZXT18, .FZXT19, .FZXT20, .FZXT21, .FZXT22, .FZXT23, .FZXT24)
            End With
        Catch ex As Exception
            rtn = -2
        End Try
        Return rtn
    End Function
End Class
Public Class en_equit_hb_LHJ_item
    Public save_time As DateTime
    Public power_on As Boolean
    Public run_modle As Integer
    Public FZXT01 As Integer
    Public FZXT02 As Integer
    Public FZXT03 As Integer
    Public FZXT04 As Integer
    Public FZXT05 As Integer
    Public FZXT06 As Integer
    Public FZXT07 As Integer
    Public FZXT08 As Integer
    Public FZXT09 As Integer
    Public FZXT10 As Integer
    Public FZXT11 As Integer
    Public FZXT12 As Integer
    Public FZXT13 As Integer
    Public FZXT14 As Integer
    Public FZXT15 As Integer
    Public FZXT16 As Integer
    Public FZXT17 As Integer
    Public FZXT18 As Integer
    Public FZXT19 As Integer
    Public FZXT20 As Integer
    Public FZXT21 As Integer
    Public FZXT22 As Integer
    Public FZXT23 As Integer
    Public FZXT24 As Integer
    Public T01 As Integer
    Public T02 As Integer
    Public T03 As Integer
    Public T04 As Integer
    Public T05 As Integer
    Public T06 As Integer
    Public T07 As Integer
    Public T08 As Integer
    Public T09 As Integer
    Public T10 As Integer
    Public T11 As Integer
    Public T12 As Integer

End Class